<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="100px">
    <el-form-item v-if="classifyId === -1" label="分类父ID" prop="classifyId">
      <el-select v-model="form.classifyId" filterable placeholder="请选择或搜索">
        <el-option
          v-for="item in listClassify"
          :key="item.classifyId"
          :label="item.classifyId+' - '+item.classifyName"
          :value="item.classifyId"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="分类名称" prop="classifyName">
      <el-input v-model="form.classifyName" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('form')">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { insertClassify, listClassifyParent, updateClassify } from '@/api/classify'

export default {
  name: 'AddOrUpdateClassify',
  props: {
    classifyId: {
      type: Number,
      default: -1
    },
    classifyName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: {
        classifyId: '',
        classifyName: ''
      },
      listClassify: [{ classifyId: 0, classifyName: '零层' }],
      rules: {
        classifyName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        classifyId: [{ required: true, message: '请选择分类父ID', trigger: ['blur', 'change'] }]
      }
    }
  },
  created() {
    if (this.classifyId === -1) {
      this.listClassifyParent()
    } else {
      this.form.classifyName = this.classifyName
    }
  },
  methods: {
    listClassifyParent() {
      listClassifyParent().then(res => {
        this.listClassify = res.data
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const form = new FormData()
          if (this.classifyId === -1) {
            form.set('classifyParentId', this.form.classifyId)
          } else {
            form.set('classifyId', String(this.classifyId))
          }
          form.set('classifyName', this.form.classifyName)
          if (this.classifyId === -1) {
            insertClassify(form).then(res => {
              if (res) {
                this.$message({ message: res.message, type: 'success' })
                this.$emit('updateDialog', false)
              }
            })
          } else {
            updateClassify(form).then(res => {
              this.$message({ message: res.message, type: 'success' })
              this.$emit('updateDialog', false)
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
